--
-- Author: shunguo.chen
-- Date: 2016-06-20 12:38:27
--
-- RewardModel

local BoxItemVo = import(".BoxItemVo")
local FateStone = import(".FateStone")
local Carnival = import(".Carnival")
local RewardHeroTreasureVo = import(".RewardHeroTreasureVo")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)
local protobuf = require "protobuf"
local table_insert = table.insert
local table_sort = table.sort
local table_remove = table.remove
require("app.ui.DelayCacheMgr")

function ClassRef:ctor(data)
	self.super.ctor(self, data)
end

function ClassRef:init()

	self._traceList = {}
	self._activityList = {}
	--活动追踪列表，显示在主界面中上位置第二行

	self._fateStoneModel = FateStone.new()
	self._fateStoneModel:init()

	self._carnival = Carnival.new()
	self._carnival:init()

	
	--local function initTestData()
		--[[
		local traceList = {
			{iconName="main_btn_qd.png", type = 4, type = 1, uuid = "4002", subType = 2, iconOrder = 5},
			{iconName="main_btn_pt.png", type = 4, type = 1, uuid = "1001", iconOrder = 1},
			{iconName="main_btn_qjkp.png", type = 4, type = 1, uuid = "2001", iconOrder = 2},
			-- {iconName="main_btn_hd5_n.png",iconOrder = 2,type = 2,uuid = "3"},
		}]]

	 	--self:setTraceList(traceList)
		
		--[[
		local activityList = {
			 {name="命运石板", order = 1, type = 1,uuid = "1001"},
			 {type = 2, name="登入送", order = 1,uuid = "2"},
			 --{type = 3, menuName="嘉年华", order = 2,uuid = "3"},
			 --{type = 5, menuName="抽卡", order = 5,uuid = "5"},
			 {type = 4, subType = 1, name="福利1", order = 4,uuid = "41"},
			 {type = 4, subType = 2, name="福利2", order = 4,uuid = "42"},
		}]]
		--self:initActivityList(activityList)
	--end
	
	-- initTestData()
		
	self._welfareData = {} --类型为4的福利数据 key为UUID,存放 月签到 和 完成任务类型
	--想省内存根本省不了
	--四日登陆数据
	self._loginAwards = {} --七日登陆
	self._threeDayLoginAwards = {} --三日登陆

	-- 命运卡牌数据
	self._cardData = nil
	self._cardUUID = nil

	self._allActivityRedPoint = {} --存放所有活动的红点 key为UUID value为true or false

	self._firstRechargeData = {} --虽然是放在福利类型的活动中 但是不清除

    self._monitorActivityIconInfo = {} --主页上运营按钮的信息

	self._monitorActivityInfo = {}
	
	self._privilegeInfo = nil -- 特权礼包信息
end

function ClassRef:clear()
	self._welfareData = nil
	self._loginAwards = nil
	self._threeDayLoginAwards = nil
	self._cardData = nil
	self._cardUUID = nil
	self._firstRechargeData = nil
	self._privilegeInfo = nil
end

function ClassRef:getFateStoneModel()
	return self._fateStoneModel
end

function ClassRef:getCarnivalModel()
	return self._carnival
end

function ClassRef:getTraceList()
	return self._traceList
end

function ClassRef:getTraceDataByIdx(idx)
	if not idx then return nil end
	return self._traceList[idx]
end

--返回活动界面右侧列表数据 显示的时候需要用到
function ClassRef:getAllActivitys()
	self:insertCDKeyAndRecommend()
	return self._activityList
end

function ClassRef:getMonthSignActivity()
	local welfareDatas = self._activityList[Enums.ActivityType.Welfare]
	if welfareDatas then
		for k, v in ipairs(welfareDatas) do
			if v.subType == Enums.ActivitySubType.Sign then
				return v
			end
		end
	end

	return nil
end

--现在福利按钮按下去直接跳转到福利的第一个活动
function ClassRef:getFirstWeflareActivity()
	local welfareDatas = self._activityList[Enums.ActivityType.Welfare]
	if welfareDatas then
		return welfareDatas[1]
	end

	return nil
end

function ClassRef:getDrawActivity()
	return self._activityList[Enums.ActivityType.Draw]
end

function ClassRef:getHeroTreasureActivity()
	local welfareDatas = self._activityList[Enums.ActivityType.Welfare]
	for k,v in pairs(welfareDatas) do
		if v.subType == Enums.ActivitySubType.HeroTreasure then
			return v
		end
	end
end

function ClassRef:getAllActivityRedPoints()
	return self._allActivityRedPoint
end

-- 清理命运卡牌的红点
function ClassRef:clearCardRedPoint()
	if self._cardUUID then
		self:setRedPoint(self._cardUUID, false)
	end
end

function ClassRef:setTraceList(data)
	self._traceList = {}
	for _, v in ipairs(data) do
		table_insert(self._traceList, v)
	end

	table_sort(self._traceList, function(a, b) return a.iconOrder < b.iconOrder end)

	--根据现在追踪的福利活动显示主界面上的面板
	local desktopController = UIHandler:getDesktopController()
	if desktopController then
		desktopController:refreshRewardBtns()
	end
end

-- 先把数据存储起来，等何时时机再初始化
function ClassRef:setAllActivitys(ary)
	self._allActivitys = ary
	if MapManager:isEnterGame() then
		self:initActivityList()
	end
end

function ClassRef:initActivityList(data)
	data = data or self._allActivitys
	self._allActivitys = nil
	
	if not data then data = {} end

	self._activityList = {}
	self._allActivityRedPoint = {}
	self._welfareData = {} --类型为4的福利数据 key为UUID,存放 月签到 和 完成任务类型
	--self._loginAwards = {} --七日登陆
	--self._threeDayLoginAwards = {} --三日登陆
	for k, v in pairs(data) do
		if v.type ~= Enums.ActivityType.Welfare then
			self._activityList[v.type] = v
			--通知服务器 获取是否领奖的消息
			if v.type == Enums.ActivityType.Into then
				--if v.subType and v.subType > 0 then
					--三日登陆
					--self:reqGetThreeDayData(v.uuid)
				--else
					--七日登陆
					--self:reqGetSignData(v.uuid)
				--end

				self:setRedPoint(v.uuid,v.redPoint > 0)

			elseif v.type == Enums.ActivityType.Draw then
				--self:reqGetCardInfos(v.uuid)
				self._cardUUID = v.uuid
				self:setRedPoint(v.uuid,v.redPoint > 0)
			elseif v.type == Enums.ActivityType.Carnival then
				self._carnival:setUUID(v.uuid)
				self:setRedPoint(v.uuid,v.redPoint > 0)
			elseif v.type == Enums.ActivityType.Fate then
				self._fateStoneModel:setUUID(v.uuid)
				self:setRedPoint(v.uuid,v.redPoint > 0)
			end
		else
			if not self._activityList[Enums.ActivityType.Welfare] then
				self._activityList[Enums.ActivityType.Welfare] = {}
			end
			table_insert(self._activityList[Enums.ActivityType.Welfare], v)
			if v.subType == Enums.ActivitySubType.Sign then
				--self:reqGetMonthSignData(v.uuid)
				self:setRedPoint(v.uuid,v.redPoint > 0)
			elseif v.subType == Enums.ActivitySubType.Give then
				-- self:reqGetTaskActivityData(v.uuid)
				--红点可以直接加了
				self:setRedPoint(v.uuid, v.redPoint > 0)
			elseif v.subType == Enums.ActivitySubType.FirstRecharge then
				-- self:reqGetFirstRechargeInfos(v.uuid)
				self:setRedPoint(v.uuid, v.redPoint > 0)
			elseif v.subType == Enums.ActivitySubType.FirstKill then
				self:reqFistKillInfos(v.uuid)
			elseif v.subType == Enums.ActivitySubType.Through then
				self:setRedPoint(v.uuid, v.redPoint > 0)
			elseif v.subType == Enums.ActivitySubType.HeroTreasure then
				self:setRedPoint(v.uuid, v.redPoint > 0)
			end
		end
	end
	self:insertCDKeyAndRecommend()

	if self._activityList[Enums.ActivityType.Welfare] then
		table_sort(self._activityList[Enums.ActivityType.Welfare], function(a, b) return a.order < b.order end)
	end

	-- if not self._activityList[Enums.ActivityType.Carnival] then
	-- 	self._activityList[Enums.ActivityType.Carnival] = {type = 3, menuName="嘉年华", order = 2,uuid = "3"}
	-- end

	-- dump(data)
end

function ClassRef:insertCDKeyAndRecommend()
	if not self._activityList[Enums.ActivityType.Welfare] then
		self._activityList[Enums.ActivityType.Welfare] = {}
	end
	-- 兑换码
	if not self:getWelfareActivityByUid("cdkey") then
		if not app.channelAPI:isReview() and UIHandler:isFunctionOpen(Constant.FUNC_TYPE_REWARD_CDKEY) then
			local info = {}
			info.name = L("redeemcode")
			info.order = 99
			info.type = Enums.ActivityType.Welfare
			info.subType = Enums.ActivitySubType.CDKey
			info.uuid = "cdkey"
			table_insert(self._activityList[Enums.ActivityType.Welfare], info)
		end
	end

end

--设置主界面上追踪福利的相应的领取与否的红点
function ClassRef:setRedPoint(uuid, isRed)
	self._allActivityRedPoint[uuid] = isRed
	--命运石板和嘉年华要特殊处理
	for i, v in ipairs(self._traceList) do
		if v.uuid == uuid then
			UD:updateWelfareNewPoint(Constant["FUNC_TYPE_REWARD_TRACE"..i],isRed)
			break
		end
	end
	app:sendMsg("RewardController", "refreshAllActivityRedPoints", self._allActivityRedPoint)
    self:refreshDestopWelfareRedPoint()
end

--刷新主界面上固定显示的一个福利红点
function ClassRef:refreshDestopWelfareRedPoint()
    for k,v in pairs(self._allActivityRedPoint) do
        if v then
            UD:updateWelfareNewPoint(Constant["FUNC_TYPE_REWARD_TRACE"],true)
            return
        end
    end

    UD:updateWelfareNewPoint(Constant["FUNC_TYPE_REWARD_TRACE"],false)
end

function ClassRef:refreshAllActivityRedPoint()
	for i, v in ipairs(self._traceList) do
		--print(Constant["FUNC_TYPE_REWARD_TRACE"..i],self._allActivityRedPoint[v.uuid])
		if v.type ~= Enums.ActivityType.Fate and v.type ~= Enums.ActivityType.Carnival then
			UD:updateWelfareNewPoint(Constant["FUNC_TYPE_REWARD_TRACE"..i],self._allActivityRedPoint[v.uuid])
		end
	end
end



function ClassRef:getActivityName(uuid)
	for k,v in ipairs(self._activityList) do
		if v.uuid == uuid then
			return L(v.name)
		end
	end
end

function ClassRef:getNextTime()
	local nextDayTime = app:getNextDayTime()
	local serverTime = math.floor(app.session:getServerTime())
	return nextDayTime - serverTime
end


-- data = {boxType=Enums.BoxType.dungeon, dungeonID="副本ID1"}
function ClassRef:addDungeonBoxType(data)
	local conf = GD:queryDungeonSubById(data.dungeonID)
	local graduate = conf.graduate

	-- 1. 为空表示两种宝箱都可以选择
	-- 2. 填成就id：需要完成指定成就才能选择宝物宝箱
	-- 3. 填1：只能开宝物宝箱
	if graduate ~= nil then
		if graduate == "1" then
			data.type = "jewel"
		else
			local ary = string.splitTwice(graduate, {"|", ":"}, true)
			local classID = UD.player.classID
			local achId
			for _,v in ipairs(ary) do
				if v[1] == classID then
					achId = v[2]
				end
			end

			if not AchievementManager:isAchievementFinished(achId) then
				data.type = "equip"
			end
		end
	end
end

----------------------------------------- request ------------------------------------

-- 领取幸运宝箱
function ClassRef:reqOpenBox(params)
	-- dump(params, "RewardModel.reqOpenBox")

	local errorCB = function()
		app:sendMsg("BoxController", "openBoxFailedCallBack")
	end
	if params.type == "guildChallenge" then -- 公会挑战宝箱领取
		app:getInst("NewguildModel"):reqGetChallengeReward( params.guildChallengeID )
	elseif params.type == "champion" then -- 冠军赛宝箱领取
		app:sendMsg("PvpModel", "reqGetChampionReward", params.championType)
	elseif params.type == "secret" then
		if params.taskIndex then
			SecretManager:reqGetTaskReward(params.taskIndex)
		else
			SecretManager:reqestGetReward()
			-- SecretManager:reqestSecretInfo()
		end
    elseif params.type == "championSeason" then --锦标赛赛季宝箱
        app:sendMsg("PvpModel", "reqSessionReward")
    elseif params.type == "challengeSeason" then -- 挑战赛赛季宝箱
    	app:sendMsg("PvpModel", "reqChallengeSeasonReward")
    elseif params.type == "associate" then -- 使用关联道具
		app:sendMsg("NewBagModel", "reqUseItem", params.uid, params.id, 1, nil, errorCB)
	elseif params.type == "eliteMatch" then --跨服精英赛
		UD.csEliteMatch:C2S_GetCrossCombatSeasonReward(params.playId)
    else
		app.session:request("pb_luckbox.C2S_RollLuckBox", {type=params.type}, function(ret)
			-- dump(ret, "pb_luckbox.C2S_RollLuckBox ret", 10)
			local items = {0,0,0,0,0}
			for i,v in ipairs(ret.luckItems) do
				items[i] = BoxItemVo.new(v)
			end
			items = table.randomCnt(items)
			app:sendMsg("BoxController", "onOpenBox", items)
			if params.type == "arenaJewel" then
				app:sendMsg("PvpModel", "onOpenPvpBox")
			end
		end)
	end
end

function ClassRef:reqGiveUpBox(tp)
	app.session:request("pb_luckbox.C2S_GiveUpLuckBox", {type=tp}, function(msg)
		-- 删除宝箱
		UD:removeLuckboxId()
	end)
end

-------------------------------------------------->>>>>>>>>>> 经验宝箱相关
-- 查询奖励
function ClassRef:reqExpBoxReward(expBoxLevel)
	app.session:request("pb_dungeon.C2S_QueryDungeonExpCard", {}, function(msg)
		if msg then
			app:sendMsg("BoxController", "onOpenExpBox", {expBoxLevel, msg.expCardRewardInfos } )
		end
	end)
end

-- 获取经验宝箱
function ClassRef:reqGotExpBoxReward( levelTemp )
	app.session:request("pb_dungeon.C2S_GainDungeonExpCard",{ level = levelTemp },function(msg)
		if msg then -- 使用成功
			app:sendMsg("BoxController", "gotExpBoxRewardSuccess" )
		end
	end)
end


--------------------------福利相关--------------------------------

--7日送
function ClassRef:reqGetSignData(activityId)
	app.session:request("pb_activity.C2S_LoginAwards",{uuid = activityId},function(msg)
		--数据
		local curIdx = msg.curIdx --可以领的最大索引值
		self._loginAwards = {}
		self._loginAwards.uuid = msg.uuid
		self._loginAwards.dayAwards = {}
		local canAndNotHaveGet = false
		for i,v in ipairs(msg.awards) do
			local loot = v.award
			loot.type = protobuf.enum_id("pb_loot.Loot.LootType", loot.type) or loot.type
			table_insert(self._loginAwards.dayAwards,{idx = i, sendIdx = i,award = loot, iconName = v.iconName,des = v.des, haveGet = v.haveGet, canGet = (i<= curIdx)})
			if not v.haveGet and i <= curIdx then
				canAndNotHaveGet = true
			end
		end

		self:setRedPoint(msg.uuid,canAndNotHaveGet)
		app:sendMsg("RewardController", "refreshCurrentPanel",self._loginAwards)
	end)
end


function ClassRef:reqGetSignAward(activityId,idx)
	--print( " --------------------->>>>>>> reqGetSignAward",activityId,idx )
	app.session:request("pb_activity.C2S_GetLoginAward",{ idx = idx, uuid = activityId },function(msg)
		--dump( msg, " --------------------->>>>>>> pb_activity.C2S_GetLoginAward " )
		if msg.ok then -- 使用成功
			local idx = msg.idx --可以领的最大索引值
			if self._loginAwards.uuid == msg.uuid then
				self._loginAwards.dayAwards[idx].haveGet = true
				app:sendMsg("RewardController", "refreshCurrentPanel",self._loginAwards)

				display.pushToast(L("tips_1150006"))
			end

			--更新是否可以领取的红点
			local canAndNotHaveGet = false
			for k,v in ipairs(self._loginAwards.dayAwards) do
				if v.canGet and not v.haveGet then
					canAndNotHaveGet = true
					break
				end
			end

			self:setRedPoint(msg.uuid,canAndNotHaveGet)
			-- 推荐活动
			if idx == 1 or idx == 6 then
				if not app.channelAPI:isReview() and not UD.localStorage:getRecommended() then
					app:sendMsg("RewardController", "openRecommendView", idx)
				end
			end
			-- 主界面付费弹窗(免费十连抽)
			if idx == 2 then
				self:checkShowAdvert(1001)
			end
		end
	end,{block = true})
end

--三日登陆

function ClassRef:reqGetThreeDayData(activityId, firstFlag)
	app.session:request("pb_activity.C2S_LoginAwards_ThreeDay",{uuid = activityId},function(msg)
		--数据
		self._threeDayLoginAwards = {}
		self._threeDayLoginAwards.uuid = msg.uuid
		self._threeDayLoginAwards.name = self:getActivityName(msg.uuid)

		self._threeDayLoginAwards.dayAwards = {}
		local canAndNotHaveGet = false
		for i,v in ipairs(msg.awards) do
			local loot = v.award
			loot.type = protobuf.enum_id("pb_loot.Loot.LootType", loot.type) or loot.type
			table_insert(self._threeDayLoginAwards.dayAwards,{idx = i, sendIdx = v.idx, award = loot, iconName = v.iconName,des = v.des, haveGet = v.haveGet, canGet = v.canGet})
			if not v.haveGet and v.canGet then
				canAndNotHaveGet = true
			end
		end
		if firstFlag then
			self:setRedPoint(msg.uuid,true)
		else
			self:setRedPoint(msg.uuid,canAndNotHaveGet)
		end

		app:sendMsg("RewardController", "refreshCurrentPanel",self._threeDayLoginAwards)
	end)
end

function ClassRef:reqGetThreeDayAward(activityId,idx)
	--print( " --------------------->>>>>>> C2S_GetLoginAward_ThreeDay",activityId,idx )
	app.session:request("pb_activity.C2S_GetLoginAward_ThreeDay",{ idx = idx, uuid = activityId },function(msg)
		--dump( msg, " --------------------->>>>>>> pb_activity.C2S_GetLoginAward_ThreeDay " )
		if msg.ok then
			local idx = msg.idx --可以领的最大索引值
			if self._threeDayLoginAwards.uuid == msg.uuid then
				local dayAwards = self._threeDayLoginAwards.dayAwards
				local canAndNotHaveGet = false
				for k,v in ipairs(dayAwards) do
					if tonumber(v.sendIdx) == tonumber(idx) then
						v.haveGet = true
					end
					if not v.haveGet and v.canGet then
						canAndNotHaveGet = true
					end
				end

				self:setRedPoint(msg.uuid,canAndNotHaveGet)
				app:sendMsg("RewardController", "refreshCurrentPanel",self._threeDayLoginAwards)
				-- 推荐活动
				if idx == 1 or idx == 3 or idx == 7 then
					if not app.channelAPI:isReview() and app:isIOS() then
						local version = string.match(device.getSystemSoftware(), "%d+%.*%d*")
						if  tonumber(version) >= 10.3 then
							app.channelAPI:showStarReview()
						else
							if idx ~= 3 and not UD.localStorage:getRecommended() then								
								app:sendMsg("RewardController", "openRecommendView", idx)
							end
						end
					end
				end
				-- 主界面付费弹窗(免费十连抽)
				if idx == 2 then
					self:checkShowAdvert(1001)
				end
				display.pushToast(L("tips_1150006"))
			end
		end
	end,{block = true})
end


--月签到数据
function ClassRef:reqGetMonthSignData(activityId)
	app.session:request("pb_activity.C2S_SignMonthAward",{uuid = activityId},function(msg)
		--数据
		local canAndNotHaveGet = false
		local signData = {}
		for k,v in ipairs(msg.cell) do
			local itemData = UD:parseLootToBagItem(v.award[1])
			table_insert(signData,{idx = k,itemData = itemData,haveGet = v.haveGet})
			if not v.haveGet and msg.curIdx >= k then
				canAndNotHaveGet = true
			end
		end
		self._welfareData[msg.uuid] = {cell = signData, curIdx = msg.curIdx, uuid = msg.uuid, name = msg.name, des = msg.des, isTrace = msg.isTrace, isDefaultTrace = msg.isDefaultTrace, iconName = msg.iconName }
		--dump(self._welfareData,"==",10)

		self:setRedPoint(msg.uuid,canAndNotHaveGet)
		app:sendMsg("RewardController", "refreshCurrentPanel",self._welfareData[msg.uuid])
	end)
end

function ClassRef:reqGetMonthSignAward(activityId,idx)
	app.session:request("pb_activity.C2S_GetSignAward",{uuid = activityId,idx = idx},function(msg)
		--数据
		--dump( msg, " --------------------->>>>>>> pb_activity.reqGetSignAward " )
		if msg.ok then
			local monthReward = self._welfareData[msg.uuid]
			if monthReward then
				if msg.idx <= #monthReward.cell then
					monthReward.cell[msg.idx].haveGet = true
					app:sendMsg("RewardController", "refreshCurrentPanel",monthReward)
					display.pushToast(L("tips_1150006"))

					local canAndNotHaveGet = false
					for k,v in ipairs(monthReward.cell) do
						if not v.haveGet and monthReward.curIdx >= k then
							canAndNotHaveGet = true
							break
						end
					end

					self:setRedPoint(msg.uuid,canAndNotHaveGet)
				else
					dump("error =============> pb_activity.C2S_GetSignAward the idx must <= #self._monthSignData.cell")
				end
			end
		end
	end)
end


--改变活动追踪状态
function ClassRef:reqChangeTrackStatus(activityId,isTrace)
	app.session:request("pb_activity.C2S_ChangeTrackStatus",{uuid = activityId,isTrace = isTrace},function(msg)
		--数据
		if msg.ok then
			local rewardInfo = self._welfareData[msg.uuid]
			if rewardInfo then
				rewardInfo.isTrace = msg.isTrace
				app:sendMsg("RewardController", "refreshCurrentPanel",rewardInfo)
			end
		end
	end)
end


--通用任务活动类型
function ClassRef:reqGetTaskActivityData(activityId)
	app.session:request("pb_activity.C2S_GetTaskActivity",{uuid = activityId},function(msg)
		--数据
		local redPoint = false
		local listData = {}
		for k,v in ipairs(msg.tasks) do
			local awards = {}
			for i,j in ipairs(v.award) do
				local itemData = UD:parseLootToBagItem(j)
				table_insert(awards, itemData)
			end
			if not v.haveGet and v.step >= v.max then
				redPoint = true
			end

			table_insert(listData,{uuid = msg.uuid, taskId = v.taskId,idx = k ,awards = awards, haveGet = v.haveGet,step = v.step or 0, max = v.max, name = v.name, des = v.des})
		end


		table_sort(listData, function(a, b)
			local aOk = a.step >= a.max
			local bOk = b.step >= b.max

			if not aOk and not bOk then return a.idx < b.idx end

			if aOk and not bOk then
				return not a.haveGet
			end

			if not aOk and bOk then
				return b.haveGet
			end

			if aOk and bOk then
				if (a.haveGet and b.haveGet) or (not a.haveGet and not b.haveGet)then
					return a.idx < b.idx
				elseif a.haveGet and not b.haveGet then
					return false
				elseif not a.haveGet and b.haveGet then
					return true
				end
			end
		end)
		self._welfareData[msg.uuid] = {tasks = listData, begTime = msg.begTime, endTime = msg.endTime, uuid = msg.uuid, name = msg.name,
			des = msg.des, isTrace = msg.isTrace, isDefaultTrace = msg.isDefaultTrace, iconName = msg.iconName,scheduleString = msg.scheduleString, autoRun = msg.autoRun}
		--dump(self._welfareData)
		self:setRedPoint(msg.uuid,redPoint)
		app:sendMsg("RewardController", "refreshCurrentPanel",self._welfareData[msg.uuid])
	end)
end

function ClassRef:reqGetTaskActivityAward(activityId, taskId)
	app.session:request("pb_activity.C2S_GetTaskActivityReward",{uuid = activityId,taskId = taskId},function(msg)
		--数据
		--dump( msg, " --------------------->>>>>>> pb_activity.C2S_GetTaskActivityReward " )
		if msg.ok then
			local rewardInfo = self._welfareData[msg.uuid]
			if rewardInfo then
				local tasks = rewardInfo.tasks
				for _,v in ipairs(tasks) do
					if v.taskId == msg.taskId then
						v.haveGet = true
						break
					end
				end
				local redPoint = false
				for _,v in ipairs(tasks) do
					if not v.haveGet and v.step >= v.max then
						redPoint = true
						break
					end
				end
				self:setRedPoint(msg.uuid,redPoint)
				app:sendMsg("RewardController", "refreshCurrentPanel",rewardInfo)
				display.pushToast(L("tips_1150006"))
			end
		end
	end)
end

-- 奇迹卡牌
function ClassRef:reqGetCardInfos(activityId)			
	app.session:request("pb_activity.C2S_GetRandomCardsInfo", {uuid = activityId}, function(msg)

		self._cardData = {}
		self._cardData.uuid = msg.uuid
		self._cardData.statusCard = {msg.statusCard1, msg.statusCard2, msg.statusCard3}
		self._cardData.timeStr = {msg.cardOpenTime1, msg.cardOpenTime2}
		self._cardData.nowCof = math.floor(msg.nowCof / 100)
		self._cardData.needGold = msg.needGold or 0
        self._cardData.remainFreeCount = msg.remainFreeCount

		app:sendMsg("RewardController", "refreshCurrentPanel", self._cardData)	
	end)		
end

function ClassRef:reqOpenMiraculousCard()
	app.session:request("pb_activity.C2S_RandomCard", {}, function(msg)			
		self._cardData.itemData = UD:parseLootToBagItem(msg.droploot[1]) 
		self._cardData.ok = msg.ok
		self._cardData.quality = msg.rate or 1

		app:sendMsg("RewardController", "refreshCurrentPanel", self._cardData)				
	end)			 
end

--首冲活动
function ClassRef:updateFirstRechargeInfo(msg)
	self._firstRechargeData = {}
	self._firstRechargeData.uuid = msg.uuid
	self._firstRechargeData.awards = {}
	self._firstRechargeData.canGet = msg.canGet --是否可以领取 没有领取则去打开首冲界面
	self._firstRechargeData.des = msg.des
	local awards = msg.award
	for k,v in ipairs(awards) do
		local itemData = UD:parseLootToBagItem(v)
		table_insert(self._firstRechargeData.awards, itemData)
	end

	self:setRedPoint(msg.uuid, msg.canGet)
	app:sendMsg("RewardController", "refreshCurrentPanel", self._firstRechargeData)
end


function ClassRef:reqGetFirstRechargeInfos(activityId)
	app.session:request("pb_activity.C2S_GetFirstChargeRewardInfo", {uuid = activityId})
end

--基金
function ClassRef:reqGetFundInfos(activityId)
	app.session:request("pb_activity.C2S_GetFundRewardInfo", {uuid = activityId},function(msg)
		local fundRewardData = {}
		fundRewardData.uuid = msg.uuid
		fundRewardData.price = msg.price
		fundRewardData.des = msg.des
		fundRewardData.goodID = msg.goodID
		fundRewardData.type = msg.type

		app:sendMsg("RewardController", "refreshCurrentPanel", fundRewardData)
	end)
end

function ClassRef:reqGetFirstChargeReward(activityId)
	DelayCacheMgr.lock(DelayCacheMgr.DelayConstant.GetPartner)
	DelayCacheMgr.lock(DelayCacheMgr.DelayConstant.GetMount)
	app.session:request("pb_activity.C2S_GetFirstChargeReward", {uuid = activityId}, function(msg)
		if msg.ok then
			--领取成功
			-- 埋点
			EM:notify("onGetFirstRechangeRewardSuccess")
			-- 如果有付费弹窗要关闭
			app:sendMsg("RewardController", "closePayNoticeView")
			--播放类似luckbox的效果
			self._firstRechargeData.canGet = false
			--将首冲活动删除 更换活动
			local welfareActivitys = self._activityList[Enums.ActivityType.Welfare]
			for k, v in ipairs(welfareActivitys) do
				if v.uuid == activityId then
					self._activityList[Enums.ActivityType.Welfare][k] = msg.chargeLogin
					break
				end
			end
			self:setRedPoint(activityId, false)
			if msg.chargeLogin then
				app:sendMsg("RewardController", "playFirstRechargeGetAwards", self._firstRechargeData.awards, msg.chargeLogin.uuid)
			else
				app:sendMsg("RewardController", "playFirstRechargeGetAwards", self._firstRechargeData.awards, nil)
			end
		else
			--领取失败
			DelayCacheMgr.unLock(DelayCacheMgr.DelayConstant.GetPartner)
			DelayCacheMgr.unLock(DelayCacheMgr.DelayConstant.GetMount)
		end
	end)
end

function ClassRef:getFirstKillConfig()
	if self.hFirstKillConfig then
		return self.hFirstKillConfig 
	end

	self.hFirstKillConfig = {}
	local cs = GD:getFirstKillConfigs()
	for k, v in pairs(cs) do
		self.hFirstKillConfig[checknumber(v.ID)] = v
	end
	return self.hFirstKillConfig
end

function ClassRef:reqFistKillInfos(activityId)
	app.session:request("pb_dungeon.C2S_QueryFirstPassInfo", {}, function(msg)
		if msg and msg.firstPassInfos then
			self.hFirstKillInfos = {}
			self.aFirstKillInfos = {}
			self:getFirstKillConfig()
			local hasRedPoint = false
			local firstReward = nil
			local firstTake = nil
			for i, v in ipairs(msg.firstPassInfos) do
				local info = {cfg = self.hFirstKillConfig[v.dungeonSubID], data=v}
				self.hFirstKillInfos[v.dungeonSubID] = info
				if info.cfg then
					table.insert(self.aFirstKillInfos, self.hFirstKillInfos[v.dungeonSubID])
				else
					print("can't find first kill config: id=", v.dungeonSubID)
				end

				if v.canGetMemberReward then
					hasRedPoint = true
				end

				if v.canGetServerReward then
					hasRedPoint = true
				end
			end
			table.sort(self.aFirstKillInfos, function(a, b)
				return checknumber(a.cfg.order) < checknumber(b.cfg.order)
			end)

			for i, v in ipairs(self.aFirstKillInfos) do
				if firstReward == nil and
				  ( v.data.canGetMemberReward or v.data.canGetServerReward  )
				then
					firstReward = i 
				end
				-- isGetMemberReward
				if firstTake == nil and (v.data.isGetServerReward == false) then
					firstTake = i
				end
			end

			self:setRedPoint(activityId, hasRedPoint)
			self._welfareData[activityId] = 
				{
					uuid=activityId, 
					info=self.aFirstKillInfos, 
					firstIndex = firstReward or firstTake or 1,
				}

			app:sendMsg("RewardController", "refreshCurrentPanel",self._welfareData[activityId])
		end
	end)
end

function ClassRef:reqGetFirstKillReward(dungeonid, rt, activityId)
	app.session:request("pb_dungeon.C2S_GetDungeonFirstPassReward", 
	{dungeonSubID = dungeonid, rewardType = rt},
	function(msg)
		if msg.ok then
			self:reqFistKillInfos(activityId)
		else
		end
	end)
end

-- 兑换码
function ClassRef:reqGetGiftCode(data)
	app.channelAPI:reqGiftCode(data, function()
		display.pushToast(L("redeemcodeTips1"))
	end)
end

--替换活动
function ClassRef:changeOldActivity(msg)
	local welfareActivitys = self._activityList[Enums.ActivityType.Welfare]
	local oldAcitity = msg.oldActivity
	for k, v in ipairs(welfareActivitys) do
		if v.uuid == oldAcitity then
			self._activityList[Enums.ActivityType.Welfare][k] = nil
			break
		end
	end

	if msg.newActivity then
		app:sendMsg("RewardController", "refreshWelfareSelected",msg.newActivity.uuid)
	else
		app:sendMsg("RewardController", "refreshWelfareSelected")
	end
end

function ClassRef:getWelfareActivityByUid(uid)
	local welfareActivitys = self._activityList[Enums.ActivityType.Welfare]
	for k, v in ipairs(welfareActivitys) do
		if v.uuid == uid then
			return v
		end
	end
end
-----------------------------------------------------
-- 特权礼包（月卡）
-----------------------------------------------------
function ClassRef:reqSuperPrivilegeInfo(param)
	app.session:request("pb_recharge.C2S_GetSuperPrivilegeInfo", {})
end

function ClassRef:getPrivilegeActivity()
	local welfareActivitys = self._activityList[Enums.ActivityType.Welfare]
	for k, v in ipairs(welfareActivitys) do
		if v.uuid == "4080" then
			return v
		end
	end
end

-----------------------------------------------------
--- 神奇宝箱
-----------------------------------------------------
function ClassRef:reqGetAmazingAwardInfo(uuid)
	-- print("C2S_GetAmazingAwardInfo-------->>>>", uuid)
	app.session:request("pb_activity.C2S_GetAmazingAwardInfo", {activityUID = uuid}, function(msg)
		-- dump(msg, "S2C_GetAmazingAwardInfo")
		self._welfareData[msg.uuid] = {
			packageInfos = msg.packageInfos, 
			uuid = msg.uuid, 
			name = msg.name,
			des = msg.des, 
			iconName = msg.iconName,
			isTrace = msg.isTrace, 
			isDefaultTrace = msg.isDefaultTrace,
			endTime = msg.endTime,
			startTime = msg.startTime}
		self._amazingBoxCost = msg.packageInfos and msg.packageInfos[1].cost
		app:sendMsg("RewardController", "refreshCurrentPanel", self._welfareData[msg.uuid])
	end)
end

function ClassRef:reqOpenAmazingAward(packageId)
	-- print("C2S_OpenAmazingAward-------->>>>", packageId)
	app:sendMsg("MallController", "setInOpenAmazingBox", true)
	app.session:request("pb_activity.C2S_OpenAmazingAward", {packageID = packageId}, function(msg)
		-- dump(msg, "S2C_OpenAmazingAward")
		local amazingAwardInfo = self._welfareData[msg.uuid]
		if amazingAwardInfo then
			amazingAwardInfo.packageInfos = msg.packageInfos
		end
		if msg.ok then			
			app:sendMsg("RewardController", "OpenAmazingAwardSuccess", amazingAwardInfo.packageInfos)
		else
			-- 播放失败的动画
			app:sendMsg("MallController", "setInOpenAmazingBox", false)
			app:sendMsg("RewardController", "OpenAmazingAwardFail", amazingAwardInfo.packageInfos)
		end
	end)
end

function ClassRef:parseMoneyInfo()
    local param = {}
    if self._amazingBoxCost then
        if self._amazingBoxCost.type == "item" then -- 物品
            param.id = self._amazingBoxCost.id
            param.num = UD:getItemAmountByTid(param.id)
            param.type = Enums.TipsType.item
        else -- 货币
            param.id = protobuf.enum_id("pb_loot.Loot.LootType", self._amazingBoxCost.type)
            param.num = UD:getDaibiValue( param.id )
            param.type = Enums.TipsType.daibi
        end
    end
    return param
end
-----------------------------------------------------
--- 付费弹窗
-----------------------------------------------------
-- 登录时候判断特权礼包信息要先请求一遍数据
function ClassRef:reqPrivilegeInfoForPayNotice()
	app.session:request("pb_recharge.C2S_GetSuperPrivilegeInfo", {}, function(msg)
		self._privilegeInfo = msg
		--app.scene:checkPayNoticeOver()
		self:checkShowAdvert(Enums.ActivitySubType.Privilege)
	end)
end

-- 根据subtype获取信息
function ClassRef:getWelfareActivityBySubType(subtype)
	local welfareActivitys = self._activityList[Enums.ActivityType.Welfare]
	for k, v in ipairs(welfareActivitys) do
		if v.subType == subtype then
			return v
		end
	end
end

-- 后续弹出的活动是哪个
function ClassRef:popUpPayNoticeActivity()
	local config = GD:queryActivityOpen()
	if not config then return end

	for i, v in ipairs(config) do
		if UD:getLevel() >= tonumber(v.openLv) then
			local welfareActivitys = self._activityList[Enums.ActivityType.Welfare] or {}
			for key, value in ipairs(welfareActivitys) do
				if tonumber(v.subType) == value.subType then
					if value.subType == Enums.ActivitySubType.Privilege then
						-- 特权礼包需要判断是否购买来关闭活动
						if self._privilegeInfo then
							if self._privilegeInfo.SuperPrivilegeID == 0 and self._privilegeInfo.SuperPrivilegeDays == 0 then
								return value.subType
							end
						end				
					else
						return value.subType
					end	
				end
			end
		end
	end
end

-- 是否还有弹出次数
function ClassRef:checkPopUpTimesBySubType(subtype)
	local config = GD:getActivityOpenBySubType(subtype)
	if config then
	  	local lastTime = UD:getValueFromGenericByKey("payNoticeLastTime"..subtype)
		local dailyTimes = UD:getValueFromGenericByKey("payNoticeDailyTimes"..subtype) or 0
		local allTimes = UD:getValueFromGenericByKey("payNoticeAllTimes"..subtype) or 0
		
		if lastTime == nil then
			return true
		elseif math.floor((app.session:getServerTime() - lastTime)/(24*60*60)) > 0 then -- 最后一次弹出的时间不是当天，当日弹出的次数清零
			dailyTimes = 0
			UD:saveGeneric("payNoticeDailyTimes"..subtype, dailyTimes)
			if tonumber(dailyTimes) < tonumber(config.dailyLimit) and tonumber(allTimes) < tonumber(config.allLimit) then
				return true
			end
		end		
	end
	return false
end

function ClassRef:checkShowAdvert(param)
	-- 首充（通关地下城判断）
	-- 特权（登录时判断）
	-- 基金（十连抽后判断）
	-- 免费十连抽（领取第二天登录豪礼后判断,无链式结构）
	-- 奇迹卡片（登录后判断,达到等级且在开启时间内,无链式结构）	
	local subType = (param == 1001 or param == 1002) and param or self:popUpPayNoticeActivity()
	if not subType or param ~= subType then return end
	local flag = self:checkPopUpTimesBySubType(subType)
	if flag then
		local info = GD:getActivityOpenBySubType(subType)
		if info then
			local isOpen = UD:getLevel() >= tonumber(info.openLv)
			if isOpen and info.open_time and info.open_time ~= "" then
				isOpen = self:checkTimeOpen(info.open_time)
			end
			if isOpen then
				app:sendMsg("RewardController", "openAdvert", info)
				local allTimes = UD:getValueFromGenericByKey("payNoticeAllTimes"..subType) or 0
				UD:saveGeneric("payNoticeAllTimes"..subType, tonumber(allTimes)+1)
			end
		end
	end
end

-- 检查是否在开启时间内
function ClassRef:checkTimeOpen(str)
	local serverTime = app:getServerTime()
	local temp = string.split(str, "|")
	if tonumber(temp[1]) == 1 then
		local startTemp = string.splitThrice(temp[2], {"-", " ", ":"})
		local endTemp = string.splitThrice(temp[3], {"-", " ", ":"})
		local list1 = {year = startTemp[1][1][1], month = startTemp[2][1][1], day = startTemp[3][1][1],
						hour = startTemp[3][2][1], min = startTemp[3][2][2]}
		local list2 = {year = endTemp[1][1][1], month = endTemp[2][1][1], day = endTemp[3][1][1], 
						hour = endTemp[3][2][1], min = endTemp[3][2][2]}	
		local startTime = os.time(list1)
		local endTime = os.time(list2)
		if serverTime > startTime and serverTime < endTime then
			return true
		end
	elseif tonumber(temp[1]) == 2 then

	elseif tonumber(temp[1]) == 3 then
		
	end
	return false
end
-----------------------------------------------------
------运营活动---------
function ClassRef:updateMonitorActivityIcon(msg)
	dump(msg)
    self._monitorActivityIconInfo = msg

	local desktopController = UIHandler:getDesktopController()
	if desktopController then
		desktopController:refreshMonitorActivityIcon()
	end

end

function ClassRef:getMonitorActivityIconInfo()
    return self._monitorActivityIconInfo
end

function ClassRef:updateMonitorActivityIconRedPoint()
    local isRed = self._monitorActivityIconInfo.redPoint and self._monitorActivityIconInfo.redPoint > 0
    UD:updateWelfareNewPoint(Constant["FUNC_TYPE_REWARD_MONITOR_TRACE"],isRed)
end

--点开运营活动按钮请求信息
function ClassRef:reqMonitorActivityInfo()
    app.session:request("pb_monitorActivity.C2S_GetOperateActivities",{},function(msg)
		self._monitorActivityInfo = {}
		dump(msg.activities,"msg")
		local sortFunc = function(a, b)
			local aOk = a.step >= a.max
			local bOk = b.step >= b.max

			if not aOk and not bOk then return a.idx < b.idx end

			if aOk and not bOk then
				return not a.haveGet
			end

			if not aOk and bOk then
				return b.haveGet
			end

			if aOk and bOk then
				if (a.haveGet and b.haveGet) or (not a.haveGet and not b.haveGet)then
					return a.idx < b.idx
				elseif a.haveGet and not b.haveGet then
					return false
				elseif not a.haveGet and b.haveGet then
					return true
				end
			end
		end


		for k1,v1 in ipairs(msg.activities) do
			local listData = {}
			for k,v in ipairs(v1.content.tasks) do
				local awards = {}
				for i,j in ipairs(v.award) do
					local itemData = UD:parseLootToBagItem(j)
					table_insert(awards, itemData)
				end

				table_insert(listData,{uuid = v1.id, isMonitor = true, taskId = v.taskId,idx = k ,awards = awards, haveGet = v.haveGet,step = v.step or 0, max = v.max, name = v.name, des = v.des})
			end

			table_sort(listData, sortFunc)

			table_insert(self._monitorActivityInfo, {tasks = listData, startTime = v1.startTime, finishTime = v1.finishTime, id = v1.id, name = v1.name,
				desc = v1.desc, redPoint = v1.redPoint, icon = v1.icon})
		end
		dump(self._monitorActivityInfo)
		app:sendMsg("RewardController", "refreshMonitorView",self._monitorActivityInfo)
    end)
end

function ClassRef:getAllMonitorActivityInfo()
    return self._monitorActivityInfo
end

function ClassRef:reqGetMonitorTaskActivityAward(activityId, taskId)
	app.session:request("pb_monitorActivity.C2S_GetOperateTaskReward",{activityID = activityId,taskID = taskId},function(msg)
		--数据
		dump( msg, " --------------------->>>>>>> pb_monitorActivity.C2S_GetOperateTaskReward " )
		if msg.ok then
			for k1,v1 in ipairs(self._monitorActivityInfo) do
				if v1.id == activityId then

					local tasks = v1.tasks
					for _,v in ipairs(tasks) do
						if v.taskId == taskId then
							v.haveGet = true
							break
						end
					end

					local redPoint = 0
					for _,v in ipairs(tasks) do
						if not v.haveGet and v.step >= v.max then
							redPoint = 1
							break
						end
					end

					v1.redPoint = redPoint
					app:sendMsg("RewardController", "refreshMonitorTaskPanel", self._monitorActivityInfo)
					display.pushToast(L("tips_1150006"))
					break
				end
			end
		end
	end,{block = true})
end


---------------------------直升---------------------------------
function ClassRef:reqLevelPromotionInfo(activityData)
	app.session:request("pb_activity.C2S_GetLevelPromotionInfo", {}, function(msg)
		if activityData then
			activityData.ids = msg.ids
			activityData.combatPower = msg.combatPower
			app:sendMsg("RewardController", "refreshCurrentPanel", activityData)
		end
	end)
end

function ClassRef:reqBuyLevelPromotion(activityData,idx)
	app.session:request("pb_activity.C2S_LevelPromotion", {id = idx}, function(msg)
		--dump(msg)
		if msg.ok then
			if activityData then
				app:sendMsg("RewardController", "showQuickLvView", msg.level)
				if #msg.ids > 0 then
					activityData.ids = msg.ids
					activityData.combatPower = msg.combatPower
					app:sendMsg("RewardController", "refreshCurrentPanel", activityData)
				else
					self:changeOldActivity({oldActivity = activityData.uuid})
				end
			end
		end
	end)
end

--英雄宝藏--
function ClassRef:reqHeroTreasureActivityInfo(activityUId)
	app.session:request("pb_activity.C2S_GetHeroTreasureInfo", {activityUID = activityUId}, function(msg)
		--dump(msg)
		local info = RewardHeroTreasureVo.new(msg)
		self._welfareData[info.uuid] = info
		--拿到数据 要更新界面
		self:setRedPoint(info.uuid,info:isRedPoint())
		app:sendMsg("RewardController", "refreshCurrentPanel", info)
	end)
end


--领取相关奖励
function ClassRef:reqGetHeroTreasureReward(activityUId, lv, isGolden)
	app.session:request("pb_activity.C2S_GetHeroTreasureReward", {activityUID = activityUId, getLevel = lv, isGolden = isGolden}, function(msg)
		--dump(msg)
		if msg.ok then

			local heroTreasureInfo = self._welfareData[activityUId]
			if heroTreasureInfo then
				heroTreasureInfo:setAwardHasGet(lv, isGolden)
				--领取成功,然后要刷新对应的界面
				self:setRedPoint(activityUId, heroTreasureInfo:isRedPoint())
				app:sendMsg("RewardController", "refreshCurrentPanel", heroTreasureInfo)
			else
				dump(activityUId,"the HeroTreasure activity is not exist")
			end
		end
	end)
end

--购买黄金宝藏
function ClassRef:reqBuyHeroTreasureGoldenReward(activityUId)
	app.session:request("pb_activity.C2S_BuyGoldenHeroTreasure", {activityUID = activityUId}, function(msg)
		--dump(msg)
		if msg.ok then

			local heroTreasureInfo = self._welfareData[activityUId]
			if heroTreasureInfo then
				heroTreasureInfo:setBuyGolden(true)
				--购买成功刷新界面
				self:setRedPoint(activityUId, heroTreasureInfo:isRedPoint())
				app:sendMsg("RewardController", "refreshCurrentPanel", heroTreasureInfo)
				display.pushToast(L("tips_1080003"))
				app:sendMsg("RewardController", "closeHeroTreasureBuyViewAfterBuyGolden")
			else
				dump(activityUId,"the HeroTreasure activity is not exist")
			end
		end
	end)
end
--购买宝藏经验
function ClassRef:reqBuyHeroTreasureExp(activityUID, buyNum)
	--dump(buyNum,"reqBuyHeroTreasureExp")
	app.session:request("pb_activity.C2S_HeroTreasureBuyExp", {activityUID = activityUID, buyNum = buyNum}, function(msg)
		--dump(msg)
		if msg.ok then

			local heroTreasureInfo = self._welfareData[activityUID]
			if heroTreasureInfo then
				heroTreasureInfo:updateExpAndLv(msg.newExp, msg.newLevel)
				--购买成功刷新界面
				self:setRedPoint(activityUID, heroTreasureInfo:isRedPoint())
				app:sendMsg("RewardController", "refreshCurrentPanel", heroTreasureInfo)
				display.pushToast(L("tips_1080003"))
				app:sendMsg("RewardController", "closeHeroTreasureBuyExpAfterBuyExp")
			else
				dump(activityUID, "the HeroTreasure activity is not exist")
			end
		end
	end)
end

return ClassRef
